<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2017/9/25
 * Time: 10:07
 */

namespace app\common\lib\filters;


use think\Env;
use think\Log;

/**
 * @deprecated
 * 敏感词过滤接口类
 *
 * Class WordFilter
 * @package app\common\lib\filters
 */
class WordFilter
{
    private static $instance;

    /**
     * @return static
     */
    public static function getInstance()
    {
        if (empty(self::$instance)) {
            self::$instance = new static(Env::get('wordfilter.host'));
        }
        return self::$instance;
    }

    private $host;

    private function __construct($host)
    {
        $this->host = $host;
    }

    /**
     * @param $text
     * @return mixed
     */
    public function filter($text) {
        $data = $this->request('/v1/query', true, ['q' => $text]);
        $ret = json_decode($data, true);
        if (1==$ret['code'] && !empty($ret['text'])) {
            return $ret['text'];
        } else {
            return $text;
        }
    }

    /**
     * @param $text
     * @return bool
     */
    public function check($text) {
        $data = $this->request('/v1/query', true, ['q' => $text]);
        $ret = json_decode($data, true);
        if (1==$ret['code'] && !empty($ret['keywords'])) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * @return array
     */
    public function getBlackWords() {
        $data = $this->request('/v1/black_words', false);

        return explode("\n", $data);
    }

    private function request($path, $isPost = true, $params = []) {

        //初始化
        $ch = curl_init();
        //设置抓取的url
        curl_setopt($ch, CURLOPT_URL, $this->host.$path);
        //设置头文件的信息作为数据流输出
        curl_setopt($ch, CURLOPT_HEADER, 0);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        if ($isPost) {
            //设置post方式提交
            curl_setopt($ch, CURLOPT_POST, 1);
            //设置post数据
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        }

        //执行命令
        $data = curl_exec($ch);
        //错误处理
        if (false === $data) {
            Log::error(curl_errno($ch).': '.curl_error($ch));
            return false;
        }
        //关闭URL请求
        curl_close($ch);

        return $data;
    }
}